<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/12
 * Time: 14:26
 */

namespace app\index\controller;


class Half extends Base
{
    /*
     * 刷新用户数据
     * eth
     * keys
     * win
     * gen
     * aff
     * num (当前轮次购买的幸运数字)
     */
    public function plyrRounds()
    {
        $pId = intval(input("pId"));
        $nId = intval(input("nId"));
        $body = [];
        // keys 和 eth
        $this->contract->call('plyrRnds_', $pId, 1, function ($err, $result) use (&$body, $pId, $nId) {
            if ($result) {
                $body['eth'] = $result['eth']->toString();
                $body['keys'] = $result['keys']->toString();
            } else {
                $this->api_error("20000", $err->getMessage());
            }

            // gen 、aff、win
            $this->contract->call('getPlayerVaults', $pId, function ($err, $result) use (&$body, $pId, $nId) {
                if ($result) {
                    $body['win'] = $result[0]->toString();
                    $body['gen'] = $result[1]->toString();
                    $body['aff'] = $result[2]->toString();
                } else {
                    $this->api_error("20000", $err->getMessage());
                }

                //用户的幸运数字（当前轮次）
                $this->contract->call('buyNumLength', $pId, $nId, function ($err, $result) use (&$body, $pId, $nId) {
                    if ($result) {
                        $numLength = intval($result[0]->toString());
                        for ($i = 0; $i < $numLength; $i++) {
                            $this->contract->call('buyNums', $pId, $nId, $i, function ($err, $result) use (&$body, $i, $numLength, $pId, $nId) {
                                $body['num'][$i] = $result[0]->toString();
                                if ($i == ($numLength - 1)) {
                                    $key = "plyrRnds_" . $pId . "_" . $nId;
                                    $this->redis->_set($key, $body, 120);
                                    $this->api_export($body);
                                }
                            });
                        }
                    } else {
                        $this->api_error("20000", $err->getMessage());
                    }
                });
            });
        });
    }

    /*
     * 从redis中获取用户数据
     * eth
     * keys
     * win
     * gen
     * aff
     * num (当前轮次购买的幸运数字)
     */
    public function plyrRoundsRedis()
    {
        $pId = intval(input("pId"));
        $nId = intval(input("nId"));
        $key = "plyrRnds_" . $pId . "_" . $nId;

        if ($this->redis->_exists($key)) {
            $data = $this->redis->_get($key);
            $this->api_export($data);
        } else {
            $this->plyrRounds();
        }
    }


}